package com.jwgf.smarowindingmachine_unity.ui;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.fragment.app.DialogFragment;

import com.jwgf.smarowindingmachine_unity.R;
import com.jwgf.smarowindingmachine_unity.logic.MachineParameterSharedPreference;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;

public class SpindleSelectedDialog extends DialogFragment {

    private Runnable callback;
    private ArrayList list = new ArrayList();
    private EditText start;
    private EditText end;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View v = inflater.inflate(R.layout.dialog_spindle_select, null);
        start = v.findViewById(R.id.start_value);
        end = v.findViewById(R.id.end_value);
        start.setText("1");
        end.setText(MachineParameterSharedPreference.getInstance().getValue(0x29, 1));
        Button addBtn = v.findViewById(R.id.add);
        final TextView tv = v.findViewById(R.id.tv);
        final HashSet<Integer> set = new HashSet<>();
        addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                list.clear();
                int min = Integer.parseInt(start.getText().toString());
                int max = Integer.parseInt(end.getText().toString());
                for (int i = min; i <= max; ++i) {
                    set.add(i);
                }
                list.addAll(set);
                Collections.sort(list);
                tv.setText(list.toString());
            }
        });


        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("选择单锭");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                if (callback != null) {
                    callback.run();
                }
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dismiss();
            }
        });
        builder.setView(v);
        return builder.create();
    }

    @Override
    public void onResume() {
        super.onResume();
//        getDialog().getWindow().setLayout(640, 480);
    }

    public void setCallBack(Runnable callback) {
        this.callback = callback;
    }

    public ArrayList<Integer> getSpindleList() {
        return list;
    }
}
